package com.nabi.starter.common.tool;


import cn.hutool.core.io.IoUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;

public class HttpContext {
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;

    public HttpContext(ServletRequest request, ServletResponse response) {
        this.request = (HttpServletRequest) request;
        this.response = (HttpServletResponse) response;
        this.session = this.request.getSession();
    }

    public HttpContext() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
        }
        this.request = requestAttributes.getRequest();
        this.response = requestAttributes.getResponse();
        this.session = request.getSession();
    }

    public void setCookie(String name, String value) {
        Cookie cookie = new Cookie(name, value);
        response.addCookie(cookie);
    }

    public void setContentType(String contentType) {
        response.setContentType(contentType);
    }

    public <T> T getSession(String name) {
        return (T) session.getAttribute(name);
    }

    public void setSession(String name, Object value) {
        session.setAttribute(name, value);
    }

    public String getInputString() {
        try {
            return IoUtil.read(request.getInputStream(), Charset.defaultCharset());
        } catch (IOException e) {
            return "";
        }
    }

    public byte[] getInputBytes() {
        try {
            return IoUtil.readBytes(request.getInputStream());
        } catch (IOException e) {
            return null;
        }
    }

    public void vriter(String data) {
        try {
            response.getWriter().print(data);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
        }
    }


    public Cookie getCookie(String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie;
            }
        }
        return null;
    }


    public Map<String, String> getQueryParam() {
        Map<String, String> query = new LinkedHashMap<>();
        Map<String, String[]> pap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : pap.entrySet()) {
            query.put(entry.getKey(), String.join(",", entry.getValue()));
        }
        return query;
    }

    public String getServeUrl() {
        String url = request.getScheme() + "://" + request.getServerName();
        if (request.getServerPort() != 80) {
            url += ":" + request.getServerPort();
        }
        url += request.getContextPath();
        return url;
    }

    public String getClientIpAddr() {
        String ip = request.getHeader("x-forwarded-for");
        System.out.println("x-forwarded-for ip: " + ip);
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public UserAgent getUserAgent() {
        String userAgent = request.getHeader("User-Agent");
        return new UserAgent(userAgent);
    }

}
